/* eslint-disable no-param-reassign */
import { Toast } from 'antd-mobile';
import type { FormInstance } from 'antd/lib/form';

export const isEmpty = (data) => {
  return !(data !== null && data !== undefined && data !== '');
};

type Sections = {
  code: string; // JBXX
  name: string; // 基本信息
  segments: Segments;
}[];

type Segments = {
  name: string;
  code: string; // userName
  type: number; // 类型
  value?: any; // 默认值
  formItemName?: string; // 给表单填写的名称
}[];

/**
 * 填充默认值到对应的字段
 * @param frames
 * @param data
 */
export const fillFramesValue: (
  /**
   * 字段
   */
  frames: any,
  /**
   * 填充的数据value
   */
  data: any,
  /**
   * 需要格外填充的规则
   */
  rules?: any,
  /**
   * 下拉数据
   */
  dicts?:any
) => { frames: any; fieldReference: any; fieldMaps } = (frames, data, rules = {}, dicts=[]) => {
  if (!Array.isArray(frames) || !data) return frames;
  const fieldReference = {} as any;
  const fieldMaps = {} as any;
  // 接口返回的字段格式不匹配
  frames = assembleFrames(frames,dicts)
  frames.forEach((item) => {
    const { sections = [], code: framesCode } = item;
    sections.forEach((sectionItem) => {
      const { code: sectionCode, segments } = sectionItem;
      const values = data[sectionCode];

      // 值是数组类型，类似紧急联系人可以有多个
      if (Array.isArray(values)) {
        const arr = [];
        if (values.length === 0) {
          segments.forEach((segmentItem) => {
            const { code: fieldCode } = segmentItem;
            const sectionData = data[sectionCode];
            segmentItem.formItemName = `${framesCode}-${sectionCode}-${fieldCode}-0`;
            // 添加格外规则
            if (rules && rules[fieldCode]) {
              Object.assign(segmentItem, rules[fieldCode]);
            }
            if (sectionData) {
              segmentItem.value = sectionData[fieldCode];
              fieldMaps[segmentItem.formItemName] = segmentItem.value;
            }
            fieldReference[segmentItem.formItemName] = segmentItem;
          });
          arr.push(segments);
        } else {
          values.forEach((valuesItem, index) => {
            let tempSegments = [...segments];
            tempSegments = tempSegments.map((segmentItem) => {
              const newSegmentItem = { ...segmentItem };
              const { code: fieldCode } = newSegmentItem;
              let value;
              // 有displayWay 代表材料上传
              if(newSegmentItem.hasOwnProperty('displayWay')) {
                if(frames?.[0]?.sceneCode === 'allMaterialsUpload'){ // 客户操作材料上传时禁止删除，让他联系客户经理操作
                  newSegmentItem.canDelete = false
                }
                const { materialsCatalogs = [] } = valuesItem
                value = (materialsCatalogs.filter(({code}) => fieldCode === code))[0]?.userMaterialsList
              }else{
                value = valuesItem[fieldCode]
              }
              // 添加格外规则
              if (rules && rules[fieldCode]) {
                Object.assign(newSegmentItem, rules[fieldCode]);
              }
              newSegmentItem.formItemName = `${framesCode}-${sectionCode}-${fieldCode}-${index}`;
              if (values.length > 1) {
                newSegmentItem.name = `${newSegmentItem.name}-${index + 1}`;
              }

              if (value) {
                newSegmentItem.value = value;
                fieldMaps[newSegmentItem.formItemName] = newSegmentItem.value;
                
              }
              fieldReference[newSegmentItem.formItemName] = newSegmentItem;

              return newSegmentItem;
            });

            /**
             * 数组形式的隐藏一个id，
             * id约定
             * 作为编辑时候用
             */
            if (valuesItem.id) {
              tempSegments.push({
                type: 0,
                code: 'id',
                formItemName: `${framesCode}-${sectionCode}-id-${index}`,
                value: valuesItem.id,
                display: 'hidden',
                name: '我是隐藏的id',
              });
            }
            arr.push(tempSegments);
          });
        }
        sectionItem.segments = arr;
      } else {
        // 不是数组的单条类型
        segments.forEach((segmentItem) => {
          const { code: fieldCode } = segmentItem;
          const sectionData = data[sectionCode];
          segmentItem.formItemName = `${framesCode}-${sectionCode}-${fieldCode}`;
          // 添加格外规则
          if (rules && rules[fieldCode]) {
            Object.assign(segmentItem, rules[fieldCode]);
          }

          if (sectionData && !isEmpty(sectionData[fieldCode])) {
            segmentItem.value = sectionData[fieldCode];
            /**
             * 存在中文是时候，
             * 类似省市区： ‘浙江省杭州市江干区’
             */
            if (sectionData[`${fieldCode}Name`]) {
              segmentItem.valueString = sectionData[`${fieldCode}Name`];
            }
            fieldMaps[segmentItem.formItemName] = segmentItem.value;
          }
          fieldReference[segmentItem.formItemName] = segmentItem;
        });
      }
    });
  });
  return { frames, fieldReference, fieldMaps };
};
const assembleFrames = (frames,dicts=[])=>{

  frames.forEach((item) => {
    const { sections = [], code: framesCode } = item;
    const newSections = []
    
    sections.forEach((_sub) => {
      const { code: subCode, segments:subSections } = _sub;
      const tempSegments =[]
        subSections.forEach((_item) => {
          
          const { code: detailCode, name: itemName, segments:itemSections } = _item;
          
          // 
          if(detailCode==='emergencyUserName'||detailCode==='emergencyPhone'){
            _item.type=0
          }
          if(detailCode==='censusPlace' || detailCode === 'homeProCityArea'){
            _item.type=9;
            _item.sourceUrl='/area/all'
          }
          if(detailCode==='inWorkDate'){
            _item.type=14;
            _item.mode='year';
            _item.format='YYYY'
          }
          // 隐藏卡分期产品
          if(detailCode === 'productMoldId'){
            _item.display='none'
          }
          if(detailCode === 'carName'){
            _item.formItemName='carName'
            _item.name='购买车型'
            _item.type=12
          }
          // 分期期数
          if(detailCode ==='repayPeriod'){
            _item.type =3
            if(!_item.dictionaryList||_item.dictionaryList.length===0){
              
              // _item.sourceUrl='/productMaintain/selectAgencyProduct'
              // _item.dataFormat
              // _item.dictionaryList=dicts.find(item=>item.key==='243')
              // _item.dictionaryList =[{value: "12", label: "12期"},{value: "18", label: "18期"},{value: "24", label: "24期"},{value: "36", label: "36期"},{value: "48", label: "48期"},{value: "60", label: "60期"}]
            }
          }
          if(detailCode === 'repayPeriod'
          ||detailCode === 'isCommissionFeeDivide'
          ||detailCode === 'principalRepayment'){
            
            _item.type =1
          }
          // 分期金额
          if(detailCode === 'stageMoney'){
            _item.type =2
            _item.unit ='元'
          }
          // 分期手续费
          if(detailCode ==='commissionFeeRate'){
            _item.unit ='%'
            _item.type =2
            _item.isEditor=0
          }
          
          
          if(detailCode==='termTo'){
            tempSegments.push({
              "code":"issueDate",
              "empty":0,
              "fieldConfigs":[
              ],
              "fieldName":"issueDate",
              "isEditor":1,
              "isRule":0,
              "mayCount":0,
              "name":"身份证有效开始日期",
              "orderBy":8,
              "type":10,
            })
            tempSegments.push({
              ..._item,
              type:11
            })
          }else{
            tempSegments.push(_item)
          }
          
        })
        _sub.segments=tempSegments
      
      
      
    })
   
    
    
  })
  return frames
}
// const sleep = (timeout) => {
//   return new Promise((r) => {
//     setTimeout(() => {
//       r(1)
//     }, timeout);
//   })
// }

export const onRespone = async (data, file) => {
  const newFile = { ...file };
  if (data.code === 0) {
    newFile.originUrl = data.data.filePath;
  } else {
    newFile.status = 'error';
    newFile.message = data.msg || '上传失败';
  }
  return newFile;
};

export const validIdUpload = (data, required, message) => {
  if (!required) return Promise.resolve();
  if (!data || (Array.isArray(data) && data.some((item) => item.status !== 'done'))) {
    return Promise.reject(message);
  }

  return Promise.resolve();
};

/**
 * 表单验证提示
 * @param param
 * @param form
 */
export const toast = ({ errorFields = [] } = {}, form?: FormInstance) => {
  if (errorFields && errorFields.length > 0) {
    if (errorFields[0] && errorFields[0].errors && errorFields[0].errors[0]) {
      const message = errorFields[0].errors[0];
      Toast.fail(message, 2.5);
      /**
       * 滚动到错误字段
       */
      if (form && form.scrollToField && errorFields[0].name) {
        form.scrollToField(errorFields[0].name);
      }
    }
  }
};

export const transformValue = (data, others = {}) => {
  const result = {};
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      const value = data[key];
      if (value !== null && value !== undefined) {
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const [framesCode, sectionsCode, segmentsCode, index] = key.split('-');

        // 数组形式的
        if (index) {
          const obj = result[sectionsCode] || [];

          if (obj[index]) {
            obj[index][segmentsCode] = value;
          } else {
            obj[index] = {
              ...others,
            };
            obj[index][segmentsCode] = value;
          }
          result[sectionsCode] = obj;
        }
        // 对象形式
        else {
          let obj = result[sectionsCode] || {};
          obj[segmentsCode] = value;
          obj = {
            ...obj,
            ...others,
          };
          result[sectionsCode] = obj;
        }
      }
    }
  }
  console.log(result);
  return result;
};
